use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::Mutex;
use tokio::time::{interval, Duration, sleep};
use webrtc::data_channel::RTCDataChannel;
use byteorder::{LittleEndian, ReadBytesExt};
use std::io::Cursor;
use bytes::Bytes;
use crate::controller::channel::{AXIS_CHANNEL, BUTTON_CHANNEL};
use crate::controller::controller_event::{controller_rumble, controller_rumble_trigger};
use super::message_channel::IS_ACK;
use once_cell::sync::Lazy;
use std::sync::atomic::Ordering;

// 使用标志位控制通道的互斥锁释放问题
// 默认false表示不能持有锁
// 当通道初始化完成后设置为true, 允许持有锁
pub static INPUT_CHANNEL_STATUS: Lazy<Arc<AtomicBool>> = Lazy::new(|| Arc::new(AtomicBool::new(false)));

#[derive(Debug, Default)]
struct GamepadState {
    index: u8,
    button_mask: u16,
    left_x: i16,
    left_y: i16,
    right_x: i16,
    right_y: i16,
    left_trigger: u16,
    right_trigger: u16,
    physical: u32,
    virtual_: u32,
}

fn current_timestamp_ms() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs_f64() * 1000.0
}
// 初始化客户端元数据
async fn send_client_metadata(input_channel: Arc<RTCDataChannel>, sequence: &mut u32) {
    loop {
        if(IS_ACK.load(Ordering::SeqCst)) {
            // 等待握手完成
            break;
        }
        // 防止异步阻塞
        sleep(Duration::from_millis(100)).await;
    }
    let mut buffer = Vec::with_capacity(15);
    let timestamp = current_timestamp_ms();

    buffer.extend_from_slice(&8u16.to_le_bytes()); // reportType = ClientMetadata
    buffer.extend_from_slice(&sequence.to_le_bytes()); // sequence
    buffer.extend_from_slice(&timestamp.to_le_bytes()); // timestamp
    buffer.push(2); // maxTouchpoints = 2

    *sequence += 1;
    let bytes = Bytes::from(buffer);
    let _ = input_channel.send(&bytes).await;
    // println!("input通道客户端元数据发送完成");
}

pub async fn input_channel_init(input_channel: Arc<RTCDataChannel>) {
    let state = Arc::new(Mutex::new(GamepadState::default()));
    let sequence = Arc::new(Mutex::new(0u32));

    // ✅ 发送初始化元数据包
    {
        let mut seq = sequence.lock().await;
        send_client_metadata(input_channel.clone(), &mut seq).await;
    }

    // ✅ 定时发送 Gamepad 数据包
    {
        // println!("input通道定时发送 Gamepad 数据包");
        let state = state.clone();
        let sequence = sequence.clone();
        let input_channel = input_channel.clone();
        tokio::spawn(async move {
            // 这里默认使用的是250Hz的采样率
            // 4ms发送一次数据包
            let mut ticker = interval(Duration::from_millis(4));
            loop {
                ticker.tick().await;

                let mut buffer = Vec::with_capacity(14 + 1 + 22);
                let mut seq = sequence.lock().await;
                let timestamp = current_timestamp_ms();

                buffer.extend_from_slice(&2u16.to_le_bytes()); // reportType = Gamepad
                buffer.extend_from_slice(&seq.to_le_bytes());  // sequence
                buffer.extend_from_slice(&timestamp.to_le_bytes()); // timestamp
                *seq += 1;
                drop(seq);

                buffer.push(1); // count = 1
                let state = state.lock().await;
                buffer.push(state.index);
                buffer.extend_from_slice(&state.button_mask.to_le_bytes());
                buffer.extend_from_slice(&state.left_x.to_le_bytes());
                buffer.extend_from_slice(&state.left_y.to_le_bytes());
                buffer.extend_from_slice(&state.right_x.to_le_bytes());
                buffer.extend_from_slice(&state.right_y.to_le_bytes());
                buffer.extend_from_slice(&state.left_trigger.to_le_bytes());
                buffer.extend_from_slice(&state.right_trigger.to_le_bytes());
                buffer.extend_from_slice(&state.physical.to_le_bytes());
                buffer.extend_from_slice(&state.virtual_.to_le_bytes());
                drop(state);
                let bytes = Bytes::from(buffer);
                let _ = input_channel.send(&bytes).await;
                // println!("input通道发送 Gamepad 数据包完成");
            }
        });
    }

    // ✅ 按钮事件监听
    {
        // println!("input通道按钮事件监听");
        let state = state.clone();
        let button_rx = BUTTON_CHANNEL.1.lock().await;
        let channel_status = INPUT_CHANNEL_STATUS.clone();
        tokio::spawn(async move {
            let mut button_rx = button_rx;
            loop {
                tokio::select! {
                    // biased关键字表示优先处理排在上面的任务----即优先处理button_rx.recv()，避免被其他任务饿死
                    biased;
                    Some(msg) = button_rx.recv() => {
                        // println!("input通道按钮事件监听: {}", msg);
                        let mut state = state.lock().await;
                        let parts: Vec<&str> = msg.split(" = ").collect();
                        if parts.len() != 2 { continue; }
                        let key = parts[0];
                        let pressed = parts[1] == "Down";

                        let bit = match key {
                            "Guide" => 2,          // Xbox 西瓜键
                            "Start" => 4,          // Menu键（中间偏右）
                            "Back" => 8,           // View键（中间偏左）
                            "A" => 16,
                            "B" => 32,
                            "X" => 64,
                            "Y" => 128,
                            "DPadUp" => 256,
                            "DPadDown" => 512,
                            "DPadLeft" => 1024,
                            "DPadRight" => 2048,
                            "LeftShoulder" => 4096,
                            "RightShoulder" => 8192,
                            "LeftStick" => 16384,
                            "RightStick" => 32768,
                            _ => 0,
                        };
                        if bit != 0 {
                            if pressed {
                                state.button_mask |= bit;
                            } else {
                                state.button_mask &= !bit;
                            }
                        }
                        drop(state); // 释放锁
                    }
                    _ = sleep(Duration::from_secs(1)) => {
                        if !channel_status.load(Ordering::SeqCst) {
                            // println!("input按钮监听监听结束");
                            break;
                        }
                    }
                }
            }
            drop(button_rx); // 释放锁
        });
    }

    // ✅ 摇杆事件监听
    {
        // println!("input通道摇杆事件监听");
        let state = state.clone();
        let axis_rx = AXIS_CHANNEL.1.lock().await;
        let channel_status = INPUT_CHANNEL_STATUS.clone();
        tokio::spawn(async move {
            let mut axis_rx = axis_rx;
            loop {
                tokio::select! {
                    // biased关键字表示优先处理排在上面的任务----即优先处理axis_rx.recv()，避免被其他任务饿死
                    biased;
                    Some(msg) = axis_rx.recv() => {
                        // println!("input通道摇杆事件监听: {}", msg);
                        let mut state = state.lock().await;
                        let parts: Vec<&str> = msg.split(" = ").collect();
                        if parts.len() != 2 { continue; }
                        let key = parts[0];
                        let value: i16 = parts[1].parse().unwrap_or(0);

                        match key {
                            "leftx" => state.left_x = value,
                            "lefty" => state.left_y = value.saturating_neg(),
                            "rightx" => state.right_x = value,
                            "righty" => state.right_y = value.saturating_neg(),
                            "triggerleft" => state.left_trigger = (value as u16)*2,
                            "triggerright" => state.right_trigger = (value as u16)*2,
                            _ => {}
                        }
                        drop(state);

                    }
                    _ = sleep(Duration::from_secs(1)) => {
                        if !channel_status.load(Ordering::SeqCst) {
                            // println!("input摇杆监听监听结束");
                            break;
                        }
                    }
                }

            }
            drop(axis_rx); // 释放锁
        });
    }

    // ✅ 接收震动数据包并驱动手柄震动
    {
        // println!("input通道接收震动数据包并驱动手柄震动");
        let input_channel = input_channel.clone();
        input_channel.on_message(Box::new(move |msg| {
            let data = msg.data.to_vec();
            let mut cursor = Cursor::new(&data);

            let report_type = cursor.read_u16::<LittleEndian>().unwrap_or(0);
            // 移除了对sequence和timestamp的读取

            if report_type & 128 != 0 {
                let rumble_type = cursor.read_u8().unwrap_or(0);
                let _gamepad_index = cursor.read_u8().unwrap_or(0);
                let left_motor = cursor.read_u8().unwrap_or(0);
                let right_motor = cursor.read_u8().unwrap_or(0);
                let left_trigger = cursor.read_u8().unwrap_or(0);
                let right_trigger = cursor.read_u8().unwrap_or(0);
                let duration = cursor.read_u16::<LittleEndian>().unwrap_or(0);
                let delay = cursor.read_u16::<LittleEndian>().unwrap_or(0);
                let repeat = cursor.read_u8().unwrap_or(0);
                // repeat 始终为235，所以忽略, 避免一直重复震动
                // println!("input通道收到震动数据包: rumble_type={}, left_motor={}, right_motor={}, left_trigger={}, right_trigger={}, duration={}, delay={}, repeat={}",
                //     rumble_type, left_motor, right_motor, left_trigger, right_trigger, duration, delay, repeat);

                let repeat = 1;
                tokio::spawn(async move {
                    if delay > 0 {
                        tokio::time::sleep(Duration::from_millis(delay as u64)).await;
                    }

                    for i in 0..repeat {
                        // println!("震动第{}次", i+1);
                        if rumble_type == 0 {
                            controller_rumble(
                                (left_motor as u32 * 65535 / 100) as u16,
                                (right_motor as u32 * 65535 / 100) as u16,
                                duration as u32,
                            );
                        }

                        controller_rumble_trigger(
                            (left_trigger as u32 * 65535 / 100) as u16,
                            (right_trigger as u32 * 65535 / 100) as u16,
                            duration as u32,
                        );

                        // if repeat > 0 {
                        //     tokio::time::sleep(Duration::from_millis(duration as u64)).await;
                        // }
                    }
                    // println!("震动结束");
                });
            }

            Box::pin(async {})
        }));
    }
    // println!("input通道初始化结束");
}